package com.cicc.beergamevirtualsimulationsystem.common.webSocket;

import com.cicc.beergamevirtualsimulationsystem.common.webSocket.config.WebSocketMessageSender;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.handler.JsonMessageHandler;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.holder.JsonMessageHandlerHolder;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.holder.WebSocketSessionHolder;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.message.AbstractJsonWebSocketMessage;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.message.Impl.SomeoneChoosesRoleJsonWebSocketMessage;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.message.JsonWebSocketMessage;
import com.cicc.beergamevirtualsimulationsystem.entity.RoomInfoManager;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {


    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        // 有特殊需要转义字符, 不报错
        MAPPER.enable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature());
    }




    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String roomId = getRoomIdFromSession(session); // 从会话中获取房间ID
        //判断这个房间是否存在
        if (roomId != null) {

        }
        WebSocketSessionHolder.addSession(roomId, session);

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 空消息不处理
        if (message.getPayloadLength() == 0) {
            return;
        }

        // 消息类型必有一属性type，先解析，获取该属性
        String payload = message.getPayload();
        JsonNode jsonNode = MAPPER.readTree(payload);
        JsonNode typeNode = jsonNode.get(AbstractJsonWebSocketMessage.TYPE_FIELD);

        System.out.println("jsonNode = " + jsonNode);

        if (typeNode == null) {
            log.error("消息类型为空，不处理");
            return;
        }else {
            String messageType = typeNode.asText();
            JsonMessageHandler handler = JsonMessageHandlerHolder.getHandler(messageType);
            if (handler == null) {
                log.error("[handleTextMessage] 消息类型（{}）不存在对应的消息处理器", messageType);
                return;
            }
            // 消息处理
            Class<? extends JsonWebSocketMessage> messageClass = handler.getMessageClass();
            JsonWebSocketMessage websocketMessageJson = MAPPER.treeToValue(jsonNode, messageClass);
            handler.handle(session, websocketMessageJson);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String roomId = (String) session.getAttributes().get("roomId");
        String userId = (String) session.getAttributes().get("userId");
        RoomInfoManager.cancelRole(roomId,userId);
        RoomInfoManager.removePlayerName(roomId,userId);
        WebSocketSessionHolder.removeSession(roomId, session);

    }
//
//    //开始倒计时
//    private void startCountdown(String roomId) {
//        new Thread(() -> {
//            int countdownTime = 60; // 每个房间的倒计时初始化为60秒
//            while (true) {
//                try {
//                    Thread.sleep(1000); // 每秒更新一次
//                    countdownTime--;
//
//                    // 广播倒计时更新给该房间的所有客户端
//                    broadcastMessage(roomId, String.valueOf(countdownTime));
//
//                    if (countdownTime == 0) {
//                        break;
//                    }
//                } catch (InterruptedException e) {
//                    Thread.currentThread().interrupt();
//                    break;
//                }
//            }
//        }).start();
//    }
//
//    private void broadcastMessage(String roomId, String message) {
//        Set<WebSocketSession> sessions = sessionsByRoom.get(roomId);
//        if (sessions != null) {
//            for (WebSocketSession session : sessions) {
//                if (session.isOpen()) {
//                    try {
//                        session.sendMessage(new TextMessage(message));
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
//    }

    private String getRoomIdFromSession(WebSocketSession session) {
        return (String) session.getAttributes().get("roomId");
    }
}